﻿Imports System.IO
Imports System.IO.Packaging
Imports System.Net
Imports System.Text
Imports System.Threading
Imports System.Globalization
Imports System.IO.Compression
Imports System.Net.Mail
Imports System.Net.WebClient



Public Class mariohacks_start
    Dim emulador As Process
    Dim nomearquivo As String
    Dim iniciogameplay As System.DateTime
    Dim ultimarom As String
    Dim serverconnect As Boolean = False

    

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        VERIFICADOR_DATA()
        listararquivos()
        icone.ShowBalloonTip(200, Environment.UserName & " @ Mario Hacks Launcher", "Clique aqui para esconder/exibir o launcher a qualquer momento!", ToolTipIcon.Info)
        nomemenu.Text = Environment.UserName.ToUpper & " @ MARIOHACKS"
        nomemenu.Enabled = False
        If File.Exists(CurDir() & "\data\Lunar IPS.exe") = False Then abas.TabPages.Remove(abapatch)
        listararquivos()
        connectbutton.PerformClick()
        searchbar.Focus()

    End Sub
    Public segundos As Integer = 7
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles cronometro.Tick
        Try
            If File.Exists(CurDir() & "\DATA\IMG\" & nomeprint & ".jpg") = False And emulador.ProcessName = "zsnesw" Then
                If segundos > 0 Then



                    icone.ShowBalloonTip(200, "CAPTURANDO TELA DE TITULO", "Por favor, aguarde " & segundos & " segundos para começar a jogar." & vbNewLine & "Estamos reconhecendo a tela inicial da ROM", ToolTipIcon.Warning)
                    segundos = segundos - 1
                Else
                    If segundos = 0 Then printartela(emulador)
                    icone.ShowBalloonTip(200, "TELA CRIADA", "Obrigado por aguardar. Você já pode começar a jogar!", ToolTipIcon.Info)

                End If
            End If
        Catch ex As Exception
        End Try
        Try
            Dim programa As String = emulador.ProcessName
            If emulador.HasExited Then
                infobox.Focus()
                segundos = 7
                Me.Show()
                cronometro.Stop()
                listararquivos()
                If programa = "zsnesw" Then
                    Dim ler As System.IO.StreamReader
                    Dim tempogameplay = emulador.ExitTime - emulador.StartTime
                    If File.Exists(CurDir() & "\data\rominfo.txt") Then
                        ler = IO.File.OpenText(CurDir() & "\data\rominfo.txt")
                        infobox.Clear()
                        infobox.AppendText(ler.ReadToEnd().Replace("This is the info for the last game you ran.", "Informações da ultima hack jogada:" & vbNewLine & vbNewLine & "Inicio do Gameplay:   " & iniciogameplay.ToString & vbNewLine & "Final do Gameplay:   " & Date.Now.ToString))
                        If tempogameplay.Hours > DateAndTime.Minute("01:00:00") Then
                            infobox.AppendText(vbNewLine & "Tempo de Gameplay:    " & tempogameplay.Hours & " horas " & tempogameplay.Minutes & "minutos")
                        Else
                            If tempogameplay.Minutes > DateAndTime.Minute("00:01:00") Then
                                infobox.AppendText(vbNewLine & "Tempo de Gameplay:    " & tempogameplay.Minutes & " minutos")
                            Else
                                infobox.AppendText(vbNewLine & "Tempo de Gameplay:    " & tempogameplay.Seconds & " segundos (só?) ")
                            End If
                        End If
                    End If
                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            Me.Show()
            cronometro.Stop()
            Exit Sub
        End Try
    End Sub

    Private Sub ImportaçãoEmMassaToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles importahack.Click
        Try
            VERIFICADOR_DATA()
            If MsgBox("Sua pasta está compactada?", MsgBoxStyle.YesNo, "Assistente de Importação de Hacks") = MsgBoxResult.No Then
                If importador.ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim DirDiretorio As DirectoryInfo = New DirectoryInfo(importador.SelectedPath)
                    Dim oFileInfoCollection() As FileInfo
                    oFileInfoCollection = DirDiretorio.GetFiles("*.smc", SearchOption.AllDirectories)
                    infobox.Clear()
                    For Each arquivo In oFileInfoCollection
                        FileCopy(arquivo.FullName, CurDir() & "\data\ROMS\" & arquivo.Name)
                        infobox.AppendText("Instalando hack: " & arquivo.Name & vbNewLine & "OK" & vbNewLine)

                    Next
                    MsgBox("Hacks adicionadas!", MsgBoxStyle.Information, Me.Text)
                    oFileInfoCollection = DirDiretorio.GetFiles("*.srm", SearchOption.AllDirectories)
                    infobox.Clear()
                    For Each arquivo In oFileInfoCollection
                        FileCopy(arquivo.FullName, CurDir() & "\data\ROMS\" & arquivo.Name)
                        infobox.AppendText("Copiando Save Game da hack: " & arquivo.Name & vbNewLine & "OK" & vbNewLine)

                    Next
                    MsgBox("Saves Games copiados!", MsgBoxStyle.Information, Me.Text)
                    listararquivos()
                End If
            Else
                achaarquivo.FilterIndex = 1
                If achaarquivo.ShowDialog = Windows.Forms.DialogResult.OK And achaarquivo.FileName.ToString.EndsWith(".zip") Then
                    ZipFile.ExtractToDirectory(achaarquivo.FileName, CurDir() & "\DATA\ROMS\IMPORTADO")
                    infobox.Text = "Importação concluida com sucesso!"
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
        End Try
    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles icone.MouseClick, login_form_show.Click
        If Me.Visible = False Then
            menuicone.Show(MousePosition)
        Else
            icone.ShowBalloonTip(600, "MARIOHACKS LAUNCHER", "Escondendo o Mariohacks Launcher, clique aqui para exibir o menu de opções rápidas.", ToolTipIcon.Info)
            Me.Hide()
        End If
    End Sub

    Private Sub JogarRomToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles loadrom.Click, jogalast.Click
        Try
            Clipboard.Clear()
            jogalast.Text = "Jogar " & listadejogos.SelectedItems.Item(0).Text
            Me.Hide()

            emulador = Process.Start(CurDir() & "\data\zsnesw.exe", "-m """ & CurDir() & "\data\roms\" & listadejogos.SelectedItems.Item(0).SubItems.Item(3).Text & "\" & listadejogos.SelectedItems.Item(0).Text & """")
            iniciogameplay = Now
            cronometro.Start()

            icone.BalloonTipIcon = ToolTipIcon.Info
            icone.BalloonTipText = "Minimizando o MarioHacks Launcher"
            icone.BalloonTipTitle = "Emulando " & listadejogos.SelectedItems.Item(0).Text
            icone.ShowBalloonTip(600)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            Me.Show()
            listararquivos()
        End Try
    End Sub


    Private Sub loadlunar_Click(sender As Object, e As EventArgs) Handles loadlunar.Click
        Try
            Me.Hide()
            emulador = Process.Start(CurDir() & "\data\lunar magic.exe", CurDir() & "\data\roms\" & listadejogos.SelectedItems.Item(0).SubItems.Item(3).Text & "\" & listadejogos.SelectedItems.Item(0).Text)
            cronometro.Start()
            icone.BalloonTipIcon = ToolTipIcon.Info
            icone.BalloonTipText = "Minimizando o MarioHacks Launcher"
            icone.BalloonTipTitle = "Editando " & listadejogos.SelectedItems.Item(0).Text
            icone.ShowBalloonTip(600)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            Me.Show()
        End Try
    End Sub

    Private Sub ApagarHackToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles apagahack.Click
        If MsgBox("Deseja realmente apagar " & listadejogos.SelectedItems.Item(0).Text & "?", MsgBoxStyle.YesNo, Me.Text) = MsgBoxResult.Yes Then
            Try
                apagaprint.PerformClick()
                Dim DirDiretorio As DirectoryInfo = New DirectoryInfo(CurDir() & "\data\ROMS\")
                Dim oFileInfoCollection() As FileInfo
                VERIFICADOR_DATA()
                oFileInfoCollection = DirDiretorio.GetFiles(listadejogos.SelectedItems.Item(0).Text.Replace(".SMC", ".*").Replace(".ZIP", ".*"), SearchOption.AllDirectories)
                For Each arquivo In oFileInfoCollection
                    File.Delete(arquivo.FullName)
                    MsgBox(arquivo.ToString & " apagado!", MsgBoxStyle.Exclamation, Me.Text)
                Next

            Catch ex As Exception
                MsgBox(ex.Message, vbCritical, ex.Source)
            End Try
        End If
        listararquivos()
    End Sub

    Private Sub deletatutoo_Click(sender As Object, e As EventArgs) Handles deletatutoo.Click
        Select Case MsgBox("ESTA AÇÃO IRA REMOVER COMPLETAMENTE TODAS AS SUAS HACKS E SAVES. É EXTREMAMENTE RECOMENDADO UM BACKUP ANTES" & vbNewLine & vbNewLine & "DESEJA FAZER BACKUP ANTES DE APAGAR SUAS HACKS??", MsgBoxStyle.YesNoCancel, Me.Text)
            Case MsgBoxResult.Yes
                Button2.PerformClick()
                ROTAPAGAR()
            Case MsgBoxResult.No
                ROTAPAGAR()
            Case Else
        End Select
    End Sub

    Private Sub deletasavegame_Click(sender As Object, e As EventArgs) Handles deletasavegame.Click
        If MsgBox("Deseja realmente apagar o Save Game da Hack " & listadejogos.SelectedItems.Item(0).Text & "?", MsgBoxStyle.YesNo, Me.Text) = MsgBoxResult.Yes Then
            Try
                File.Delete(CurDir() & "\data\ROMS\" & listadejogos.SelectedItems.Item(0).SubItems.Item(3).Text & "\" & listadejogos.SelectedItems.Item(0).Text.ToUpper.Replace(".SMC", ".SRM"))
                infobox.Text = listadejogos.SelectedItems.Item(0).Text.ToUpper.Replace(".SMC", ".SRM") & " apagado!"
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            End Try
        End If
    End Sub

    Private Sub deletasavestate_Click(sender As Object, e As EventArgs) Handles deletasavestate.Click
        If MsgBox("Deseja realmente apagar os Saves States da hack " & listadejogos.SelectedItems.Item(0).Text & "?", MsgBoxStyle.YesNo, Me.Text) = MsgBoxResult.Yes Then
            Try
                infobox.Clear()
                VERIFICADOR_DATA()
                Dim DirDiretorio As DirectoryInfo = New DirectoryInfo(CurDir() & "\data\ROMS\")
                Dim oFileInfoCollection() As FileInfo
                oFileInfoCollection = DirDiretorio.GetFiles(listadejogos.SelectedItems.Item(0).Text.ToUpper.Replace(".SMC", "") & ".*", SearchOption.AllDirectories)
                For Each arquivo As FileInfo In oFileInfoCollection
                    If arquivo.Extension <> ".SMC" Then
                        If arquivo.Extension <> ".SRM" Then
                            File.Delete(arquivo.FullName)
                            infobox.AppendText(arquivo.Name & " apagado!" & vbNewLine)
                        End If
                    End If
                Next

            Catch ex As Exception
                MsgBox(ex.Message, vbCritical, ex.Source)
            End Try
        End If
    End Sub

    Private Sub PesquisarReview2(sender As Object, e As EventArgs) Handles mariohacksfind.Click, googlefind.Click
        If sender.name = "googlefind" Then
            Process.Start("https://www.google.com.br/search?q=Super+Mario+Hack:+" & listadejogos.SelectedItems.Item(0).Text.ToLower.Replace(".smc", "").Replace("_", "+").Replace("&", "%26"))
        Else
            Process.Start("http://mariohacks.blogspot.com.br/search/label/?q=" & listadejogos.SelectedItems.Item(0).Text.ToLower.Replace(".smc", "").Replace("_", "+").Replace("&", "%26") & "&r=0&submit=Vai!")
        End If
    End Sub

    Private Sub PesquisarReview(sender As Object, e As EventArgs) Handles blogit.Click, googleit.Click
        If sender.name = "googleit" Then
            Process.Start("https://www.google.com.br/search?q=Super+Mario+Hack:+" & ftplist.SelectedItems.Item(0).Text.ToString.Replace("_", "+").Replace(".smc", "").Replace("&", "%26"))
        Else
            Process.Start("http://mariohacks.blogspot.com.br/search/label/?q=" & ftplist.SelectedItems.Item(0).Text.ToString.Replace("_", "+").Replace(".smc", "").Replace("&", "%26") & "&r=0&submit=Vai!")
        End If
    End Sub

    Private Sub btinstall_Click(sender As Object, e As EventArgs) Handles instalarhack.Click, btinstallpatch.Click
        Try
            VERIFICADOR_DATA()
            If MsgBox("Sua HACK está compactada (formato .zip)?", MsgBoxStyle.YesNo, "Assistente de Instalação de HACK") = MsgBoxResult.No Then
                If sender.name = btinstallpatch.Name Then achaarquivo.FilterIndex = 3 Else achaarquivo.FilterIndex = 1
                If achaarquivo.ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim info As FileInfo
                    info = My.Computer.FileSystem.GetFileInfo(achaarquivo.FileName)
                    If info.Extension = ".IPS" Or info.Extension = ".ips" Then
                        FileCopy(achaarquivo.FileName, CurDir() & "\data\IPS\" & achaarquivo.SafeFileName)
                    Else
                        FileCopy(achaarquivo.FileName, CurDir() & "\data\ROMS\" & achaarquivo.SafeFileName)
                    End If
                End If
            Else
                achaarquivo.FilterIndex = 2
                If achaarquivo.ShowDialog = Windows.Forms.DialogResult.OK And achaarquivo.FileName.ToString.EndsWith(".zip") Then
                    ZipFile.ExtractToDirectory(achaarquivo.FileName, CurDir() & "\DATA\ROMS\IMPORTADO")
                    infobox.Text = "Instalação concluida com sucesso!"
                End If
            End If
            listararquivos()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
        End Try
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles limparcfg.Click
        Try
            If emucfgbox.Checked Then File.Delete(CurDir() & "\data\zsnesw.cfg")
            If controlesbox.Checked Then File.Delete(CurDir() & "\data\zinput.cfg")
            If moviebox.Checked Then File.Delete(CurDir() & "\data\zmovie.cfg")
            If fontbox.Checked Then File.Delete(CurDir() & "\data\zfont.txt")
            MsgBox("Configurações apagadas", MsgBoxStyle.Information, Me.Text)
        Catch ex As Exception
            MsgBox(ex.Source, MsgBoxStyle.Critical, ex.Message)
        End Try

    End Sub

    Private Sub lipsbt_Click(sender As Object, e As EventArgs) Handles lipsbt.Click
        If File.Exists(CurDir() & "\data\Lunar IPS.exe") = False Then
            MsgBox("LUNAR IPS.exe não instalado! Localize uma cópia.", MsgBoxStyle.Exclamation, Me.Text)
            If localizaemulador.ShowDialog() = Windows.Forms.DialogResult.OK Then
                File.Copy(localizaemulador.FileName, CurDir() & "\data\Lunar IPS.exe")
                abas.TabPages.Add(abapatch)
                verificarprogs()
                sender.performclick()
            Else
                Process.Start("http://fusoya.eludevisibility.org/lips/")
            End If
        Else
            Me.Hide()
            emulador = Process.Start(CurDir() & "\data\lunar ips.exe")
            cronometro.Start()
            icone.BalloonTipIcon = ToolTipIcon.Info
            icone.BalloonTipText = "Minimizando o MarioHacks Launcher"
            icone.BalloonTipTitle = "iniciando " & sender.text.replace("Abrir ", "")
            icone.ShowBalloonTip(600)
        End If
    End Sub

    Private Sub emubt_Click(sender As Object, e As EventArgs) Handles emubt.Click
        Try
            VERIFICADOR_DATA()
            Me.Hide()
            emulador = Process.Start(CurDir() & "\data\zsnesw.exe")
            cronometro.Start()
            icone.BalloonTipIcon = ToolTipIcon.Info
            icone.BalloonTipText = "Minimizando o MarioHacks Launcher"
            icone.BalloonTipTitle = "iniciando " & sender.text.replace("Abrir ", "")
            icone.ShowBalloonTip(600)
        Catch ex As Exception
            infobox.Text = "ERRO: " & ex.Source & " - " & ex.Message
        End Try

    End Sub

    Private Sub lunabt_Click(sender As Object, e As EventArgs) Handles lunabt.Click
        If File.Exists(CurDir() & "\data\Lunar Magic.exe") = False Then
            MsgBox("Editor LUNAR MAGIC.EXE não instalado! Localize uma cópia.", MsgBoxStyle.Exclamation, Me.Text)
            If localizaemulador.ShowDialog() = Windows.Forms.DialogResult.OK Then
                File.Copy(localizaemulador.FileName, CurDir() & "\data\Lunar Magic.exe")
                sender.performclick()
                verificarprogs()
            Else
                Process.Start("http://fusoya.eludevisibility.org/lm/program.html")
            End If
        Else
            Me.Hide()
            emulador = Process.Start(CurDir() & "\data\Lunar Magic.exe")
            cronometro.Start()
            icone.BalloonTipIcon = ToolTipIcon.Info
            icone.BalloonTipText = "Minimizando o MarioHacks Launcher"
            icone.BalloonTipTitle = "iniciando " & sender.text.replace("Abrir ", "")
            icone.ShowBalloonTip(600)

        End If
    End Sub

    Sub pegarips()
        Try
            VERIFICADOR_DATA()
            Dim DirDiretorio As DirectoryInfo = New DirectoryInfo(CurDir() & "\data\IPS\")
            Dim oFileInfoCollection() As FileInfo
            oFileInfoCollection = DirDiretorio.GetFiles("*.ips")
            listaips.Rows.Clear()
            For Each arquivo In oFileInfoCollection
                listaips.Rows.Add(arquivo.ToString)
                infobox.AppendText("Carregando IPS: " & arquivo.Name & vbNewLine)

            Next
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
        End Try
    End Sub

    Sub verificarprogs()
        If Not File.Exists(CurDir() & "\data\Lunar Magic.exe") Then loadlunar.Enabled = False Else loadlunar.Enabled = True
        If Not File.Exists(CurDir() & "\data\Lunar IPS.exe") Then listaips.Enabled = False Else listaips.Enabled = True

    End Sub

    Private Sub AplicarPatchIPSToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AplicarPatchIPSToolStripMenuItem.Click
        Try
            Me.Hide()
            emulador = Process.Start(CurDir() & "\data\lunar IPS.exe", CurDir() & "\data\IPS\" & listaips.CurrentCell.Value.ToString)
            cronometro.Start()
            icone.BalloonTipIcon = ToolTipIcon.Info
            icone.BalloonTipText = "Minimizando o MarioHacks Launcher"
            icone.BalloonTipTitle = "Abrindo Patch " & listaips.CurrentCell.Value.ToString
            icone.ShowBalloonTip(600)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            Me.Show()
        End Try
    End Sub

    Private Sub ApagarPatchIPSToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ApagarPatchIPSToolStripMenuItem.Click
        Try
            If MsgBox("Deseja realmente apagar " & listaips.CurrentCell.Value.ToString & "?", MsgBoxStyle.YesNo, Me.Text) = MsgBoxResult.Yes Then
                Try
                    Dim DirDiretorio As DirectoryInfo = New DirectoryInfo(CurDir() & "\data\IPS\")
                    Dim oFileInfoCollection() As FileInfo
                    VERIFICADOR_DATA()
                    oFileInfoCollection = DirDiretorio.GetFiles(listaips.CurrentCell.Value.ToString)
                    infobox.Clear()
                    For Each arquivo In oFileInfoCollection
                        File.Delete(arquivo.FullName)
                        infobox.AppendText("Apagando Patch: " & arquivo.FullName & vbNewLine & "OK" & vbNewLine)

                    Next
                Catch ex As Exception
                    MsgBox(ex.Message, vbCritical, ex.Source)
                End Try
            End If
            pegarips()
        Catch ex As Exception
            pegarips()
        End Try
    End Sub

    Private Sub emucfgbox_CheckedChanged(sender As Object, e As EventArgs) Handles emucfgbox.CheckedChanged, controlesbox.CheckedChanged, moviebox.CheckedChanged, fontbox.CheckedChanged
        If emucfgbox.Checked Or controlesbox.Checked Or moviebox.Checked Or fontbox.Checked = True Then limparcfg.Enabled = True Else limparcfg.Enabled = False
    End Sub

    Private Sub listaips_CellContentClick_1(sender As Object, e As EventArgs) Handles listaips.Click, listaips.CellContentClick
        menuips.Show(MousePosition)
    End Sub

    Private Sub importpatch_Click(sender As Object, e As EventArgs) Handles importpatch.Click
        Try
            If importador.ShowDialog = Windows.Forms.DialogResult.OK Then
                Dim DirDiretorio As DirectoryInfo = New DirectoryInfo(importador.SelectedPath)
                Dim oFileInfoCollection() As FileInfo
                VERIFICADOR_DATA()
                oFileInfoCollection = DirDiretorio.GetFiles("*.IPS", SearchOption.AllDirectories)
                infobox.Clear()
                For Each arquivo In oFileInfoCollection
                    FileCopy(arquivo.FullName, CurDir() & "\data\IPS\" & arquivo.Name)
                    infobox.AppendText("Instalando IPS: " & arquivo.Name & vbNewLine & "OK" & vbNewLine)
                Next
                MsgBox("Patches adicionados!", MsgBoxStyle.Information, Me.Text)
                pegarips()
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try
    End Sub

    Private Sub ajudabt_Click(sender As Object, e As EventArgs) Handles ajudabt.Click
        Process.Start("http://mariohacks.url.ph")

    End Sub

    Private Sub FecharMariohacksLauncherToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles exitl.Click
        If MsgBox("Deseja Fechar o Mariohacks Launcher?", MsgBoxStyle.YesNo, Me.Text) = MsgBoxResult.Yes Then Me.Close()
    End Sub

    Private Sub AbrirNavegadorToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles abreferramentas.Click, abrehacks.Click, abrepatch.Click
        Me.Show()
        Select Case sender.text.replace("Abrir ", "")
            Case "HACKS"
                abas.SelectedTab = abajogos
            Case "FERRAMENTAS"
                abas.SelectedTab = abaferramentas
                Me.WindowState = FormWindowState.Normal
            Case "PATCHS"
                abas.SelectedTab = abapatch
        End Select
    End Sub

    Private Sub ToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem2.Click
        Me.Show()
        ajudabt.PerformClick()
    End Sub

    Private Sub Dicas_CheckedChanged(sender As Object, e As EventArgs) Handles Dicas.CheckedChanged
        If sender.checked Then dica.Active = True Else dica.Active = False
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Try
            Dim pasta As New FolderBrowserDialog
            If pasta.ShowDialog = Windows.Forms.DialogResult.OK Then
                ZipFile.CreateFromDirectory(CurDir(), pasta.SelectedPath & "\" & Environment.UserName.ToString & "_MarioHacksLauncher_BACKUP.zip")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
        End Try


    End Sub

    Sub ROTAPAGAR()
        Try
            VERIFICADOR_DATA()
            Dim DirDiretorio As DirectoryInfo = New DirectoryInfo(CurDir() & "\data\roms\")
            Dim oFileInfoCollection() As FileInfo
            infobox.Clear()
            oFileInfoCollection = DirDiretorio.GetFiles("*.*", SearchOption.AllDirectories)
            For Each arquivo In oFileInfoCollection
                File.Delete(arquivo.FullName)
                infobox.AppendText("Apagando: " & arquivo.Name & vbNewLine)
            Next
            Dim log As String = infobox.Text
            listararquivos()
            infobox.Text = log
        Catch ex As Exception
            MsgBox(ex.Message, vbCritical, ex.Source)
        End Try

    End Sub

    Private Sub listaips_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles listaips.CellContentClick
        If listaips.RowCount > 0 Then menuips.Show(MousePosition)
    End Sub




    Private Sub download_hack(linha As ListViewItem)

        ' ----- Faz o Download do arquivo definido via FTP e salva em uma pasta da aplicação
        Dim readBuffer(4095) As Byte
        Dim contador As Integer
        Dim arquivoRequisitado As FtpWebRequest
        Dim respostaFTP As FtpWebResponse
        Dim respostaStream As IO.Stream
        Dim arquivoSaida As IO.FileStream
        Dim pastaDestino As String
        Dim tamanho As String

        ' ----- Obtem local onde irá salvar o arquivo
        pastaDestino = CurDir() & "\data\roms\" & linha.SubItems.Item(2).Text & "\" & linha.Text
        Try

            ' ----- Faz a conexao com o arquivo no site FTP
            arquivoRequisitado = CType(FtpWebRequest.Create(New Uri("ftp://185.28.21.148/hacks/" & ftplist.SelectedItems.Item(0).SubItems.Item(2).Text & "/" & ftplist.SelectedItems.Item(0).Text)), FtpWebRequest)

            arquivoRequisitado.Credentials = New NetworkCredential("u956709130", "Senha1234")
            arquivoRequisitado.UseBinary = True
            arquivoRequisitado.KeepAlive = False
            arquivoRequisitado.Method = WebRequestMethods.Ftp.GetFileSize
            respostaFTP = CType(arquivoRequisitado.GetResponse, FtpWebResponse)
            tamanho = respostaFTP.ContentLength
            barra.Maximum = CType(tamanho, Long)
            respostaFTP.Close()



            ' ----- Abre um canal de transmissão para o arquivo
            arquivoRequisitado = CType(FtpWebRequest.Create(New Uri("ftp://185.28.21.148/hacks/" & ftplist.SelectedItems.Item(0).SubItems.Item(2).Text & "/" & ftplist.SelectedItems.Item(0).Text)), FtpWebRequest)

            arquivoRequisitado.Credentials = New NetworkCredential("u956709130", "Senha1234")
            arquivoRequisitado.UseBinary = True
            arquivoRequisitado.KeepAlive = False
            arquivoRequisitado.Method = WebRequestMethods.Ftp.DownloadFile

            ' ----- Abre um canal de transmissão para o arquivo
            respostaFTP = CType(arquivoRequisitado.GetResponse, FtpWebResponse)
            respostaStream = respostaFTP.GetResponseStream
            arquivoSaida = New FileStream(pastaDestino, FileMode.Create)
            barra.Visible = True
            ' ----- Salva o conteúdo do arquivo de saida bloco a bloco
            Do

                contador = respostaStream.Read(readBuffer, 0, readBuffer.Length)
                arquivoSaida.Write(readBuffer, 0, contador)
                infobox.Text = "Baixando " & linha.Text & "... Aguarde... " & vbNewLine & "Total: " & arquivoSaida.Length * 10 ^ -6 & " MB de " & tamanho * 10 ^ -6 & " MB"
                barra.Value = arquivoSaida.Length
                icone.ShowBalloonTip(200, "DOWNLOAD DE ROM", CType(barra.Value * 100 / barra.Maximum, Integer) & "%, Aguarde...", ToolTipIcon.Info)
                linha.SubItems.Item(1).Text = "BAIXANDO"
                Update()
            Loop Until contador = 0
            barra.Visible = False
            icone.ShowBalloonTip(200, "DOWNLOAD DE ROM", "Download Completo!", ToolTipIcon.Info)
            linha.SubItems.Item(1).Text = "BAIXADO"
        Catch ex As Exception
            barra.Visible = False
            icone.ShowBalloonTip(2000, ex.Source, ex.Message, ToolTipIcon.Error)
            Return
        End Try

        ' ----- libera recursos.
        respostaStream.Close()
        arquivoSaida.Flush()
        arquivoSaida.Close()
        respostaFTP.Close()
        infobox.AppendText(vbNewLine & "Download da HACK " & linha.Text & " completo!" & vbNewLine & vbNewLine)
        listararquivos()
    End Sub

    Function pegadata(linha As ListViewItem)
        Try
            ' ----- Pega tamanho do arquivo definido via FTp
            Dim data As String
            Dim arquivoRequisitado As FtpWebRequest
            Dim respostaFTP As FtpWebResponse
            ' ----- Faz a conexao com o arquivo no site FTP
            arquivoRequisitado = CType(FtpWebRequest.Create(New Uri("ftp://185.28.21.148/hacks/" & linha.SubItems.Item(2).Text & "/" & linha.Text)), FtpWebRequest)

            arquivoRequisitado.Credentials = New NetworkCredential("u956709130", "Senha1234")

            arquivoRequisitado.KeepAlive = False
            arquivoRequisitado.UseBinary = True
            arquivoRequisitado.Method = WebRequestMethods.Ftp.GetDateTimestamp

            ' ----- Abre um canal de transmissão para o arquivo
            respostaFTP = CType(arquivoRequisitado.GetResponse, FtpWebResponse)
            data = respostaFTP.StatusDescription.Substring(4)
            Dim novadata As String = ""
            For Each caractere As Char In data.ToCharArray
                If novadata.Length = 4 Then novadata = novadata & "/"
                If novadata.Length = 7 Then novadata = novadata & "/"
                If novadata.Length = 10 Then novadata = novadata & " "
                If novadata.Length = 13 Then novadata = novadata & ":"
                If novadata.Length = 16 Then novadata = novadata & ":"
                novadata = novadata & caractere
            Next
            Return Convert.ToDateTime(novadata)
        Catch ex As Exception
            Return "Indisponivel"
        End Try
    End Function

    Sub listarFTP(DIFICULDADE As String)

        Dim dirFtp As FtpWebRequest = CType(FtpWebRequest.Create("ftp://185.28.21.148/hacks/" & DIFICULDADE & "/"), FtpWebRequest)
        dirFtp.KeepAlive = False

        dirFtp.Credentials = New NetworkCredential("u956709130", "Senha1234")

        dirFtp.Method = WebRequestMethods.Ftp.ListDirectory
        Dim tamanho As Integer = CInt(dirFtp.GetResponse().ContentLength)
        ' Obtem o resultado do comando
        Dim reader As New StreamReader(dirFtp.GetResponse().GetResponseStream())

        Do While reader.Peek() >= 0
            Dim hackname = reader.ReadLine
            Dim status As String
            If hackname.ToUpper.EndsWith(".SMC") Or hackname.ToUpper.EndsWith(".ZIP") Then
                Dim cogumelo As Integer
                If File.Exists(CurDir() & "\DATA\ROMS\" & DIFICULDADE & "\" & hackname) Then
                    status = "BAIXADO"
                    cogumelo = 0
                Else
                    status = "NÃO BAIXADO"
                    cogumelo = 6
                End If

                ftplist.Items.Add(hackname.ToUpper, cogumelo)
                ftplist.Items(ftplist.Items.Count - 1).SubItems.Add(status)
                ftplist.Items(ftplist.Items.Count - 1).SubItems.Add(DIFICULDADE)
                ftplist.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
                ftplist.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
            End If
        Loop
        ' Fechar o stream aberto.
        reader.Close()

    End Sub

    Sub rotinadedownload()
        Try
            Dim dataservidor As Date = pegadata(ftplist.SelectedItems.Item(0))
            If File.Exists(CurDir() & "\DATA\ROMS\" & ftplist.SelectedItems.Item(0).SubItems.Item(2).Text & "\" & ftplist.SelectedItems.Item(0).Text) = True Then
                Dim dataarquivo As Date = File.GetCreationTime(CurDir() & "\DATA\ROMS\" & ftplist.SelectedItems.Item(0).SubItems.Item(2).Text & "\" & ftplist.SelectedItems.Item(0).Text)
                If dataarquivo < dataservidor Then
                    If MsgBox("Deseja atualizar a hack " & ftplist.SelectedItems.Item(0).Text & "?", MsgBoxStyle.Information + MsgBoxStyle.YesNo, "ROM DOWNLOADER") = MsgBoxResult.Yes Then
                        download_hack(ftplist.SelectedItems.Item(0))
                        File.SetCreationTime(CurDir() & "\DATA\ROMS\" & ftplist.SelectedItems.Item(0).SubItems.Item(2).Text & "\" & ftplist.SelectedItems.Item(0).Text, dataservidor)
                    Else
                        Exit Sub
                    End If
                Else
                    MsgBox("Sua ROM já está atualizada!", MsgBoxStyle.Information, "ROM DOWNLOADER")
                    Exit Sub
                End If
            Else
                download_hack(ftplist.SelectedItems.Item(0))
                File.SetCreationTime(CurDir() & "\DATA\ROMS\" & ftplist.SelectedItems.Item(0).SubItems.Item(2).Text & "\" & ftplist.SelectedItems.Item(0).Text, dataservidor)
            End If
            listararquivos()
        Catch ex As Exception
            infobox.Text = "Não foi possivel iniciar o download da HACK  '" & ftplist.SelectedItems.Item(0).Text & "'. Aparentemente a HACK está corrompida." & vbNewLine & "Mensagem de erro: " & ex.Source & " - " & ex.Message
        End Try
    End Sub

    Private Sub ftplist_CellContentClick(sender As Object, e As MouseEventArgs) Handles ftplist.MouseDoubleClick
        rotinadedownload()
    End Sub



    Private Sub conectaservidor(sender As Object, e As EventArgs) Handles connectbutton.Click
        If MsgBox("Deseja " & connectbutton.Text.ToLower & " do MarioHacks Launcher?", MsgBoxStyle.YesNo + MsgBoxStyle.Exclamation, "Mariohacks Launcher".ToUpper) = MsgBoxResult.Yes Then
            If serverconnect = False Then
                serverconnect = True
                connectbutton.Text = "Desconectar do Servidor"
                LISTARSERVIDOR()
            Else
                serverconnect = False
                connectbutton.Text = "Conectar ao Servidor"
                ftplist.Items.Clear()
            End If
        End If

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles abredir.Click
        Process.Start(CurDir())
    End Sub

    Private Sub downloadit_Click(sender As Object, e As EventArgs)
        For Each linha As ListViewItem In ftplist.SelectedItems
            download_hack(linha)
        Next
    End Sub

    Private Sub mostradetalhes_Click(sender As Object, e As EventArgs) Handles youtubeit.Click
        Process.Start("https://www.youtube.com/results?search_query=" & listadejogos.SelectedItems.Item(0).Text.Replace("_", "+").Replace(".smc", "").Replace("&", "%26"))
    End Sub

    Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
        Process.Start("https://www.youtube.com/results?search_query=" & ftplist.SelectedItems.Item(0).Text.ToString.Replace("_", "+").Replace(".smc", "").Replace("&", "%26"))
    End Sub

    Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
        Try
            Dim Mail As New MailMessage
            Mail.Subject = Environment.UserName & " te enviou uma HACK via MarioHacksLauncher"
            Dim fulanoemail = InputBox("Olá " & Environment.UserName & ", digite o email do seu amigo(a) que irá receber a HACK:" & vbNewLine & vbNewLine & "DICA: Você pode adicionar varios emails separados por virgula(,).", "Mariohacks Launcher Hacksender")
            If String.IsNullOrWhiteSpace(fulanoemail) = False Then
                Mail.To.Add(fulanoemail)
                Mail.From = New MailAddress("suporte@mariohacks.url.ph")
                Mail.IsBodyHtml = True
                Mail.Body = "<center><p><img src='http://mariohacks.url.ph/IMG/banner.png' width='460' height='30'></p>  <h1>HACKSENDER</h1> <p>Seu colega <strong>" & Environment.UserName & "</strong> enviou uma cópia da HACK <strong>" & listadejogos.SelectedItems.Item(0).Text & "</strong> para você através do <a href='http://mariohacks.url.ph'>MarioHacks Launcher</a>. A cópia da Hack se encontra em anexo. Encontre outras HACKS em nosso sistema! Faça o <a href='http://mariohacks.url.ph/#download'>download</a> da ferramenta em nosso site agora mesmo e descubra o universo das hacks de Super Mario World!</p><p>Se você acredita ter recebido este email por engano, por favor, pode deleta-lo imediatamente!</p></center>"
                Dim SMTP As New SmtpClient("mx1.hostinger.com.br")
                SMTP.Credentials = New System.Net.NetworkCredential("suporte@mariohacks.url.ph", "Senha1234")
                SMTP.Port = 2525
                Mail.Attachments.Add(New Attachment(CurDir() & "\data\roms\" & listadejogos.SelectedItems.Item(0).SubItems(3).Text & "\" & listadejogos.SelectedItems.Item(0).Text))
                infobox.Text = "Aguarde... estamos enviando seu email..."
                SMTP.Send(Mail)
                MsgBox("Email enviado com sucesso!", MsgBoxStyle.Information, "HACKSENDER")
            Else
                MsgBox("Você não preencheu os campos corretamente!", MsgBoxStyle.Exclamation, "HACKSENDER")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
        End Try

    End Sub

    Private Sub sendhackbt_Click(sender As Object, e As EventArgs) Handles hacksender.Click
        enviarhack.Show()
    End Sub

    Private Sub ftplist_MouseClick(sender As Object, e As MouseEventArgs) Handles ftplist.MouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then menuservidor.Show(MousePosition)

    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles filtrobt.Click
        If sender.text = "TODAS" Then
            sender.text = "KAIZO_HACK"
            LISTARSERVIDOR()
            listararquivos()
            Exit Sub
        End If

        If sender.text = "KAIZO_HACK" Then
            sender.text = "HACK"
            LISTARSERVIDOR()
            listararquivos()
            Exit Sub
        End If

        If sender.text = "HACK" Then
            sender.text = "ROM_ORIGINAL"
            LISTARSERVIDOR()
            listararquivos()
            Exit Sub
        End If
        If sender.text = "ROM_ORIGINAL" Then
            sender.text = "TODAS"
            LISTARSERVIDOR()
            listararquivos()
            Exit Sub
        End If



    End Sub

    Sub LISTARSERVIDOR()
        ftplist.Items.Clear()
        If serverconnect = True Then
            Try


                If filtrobt.Text = "TODAS" Then
                    listarFTP("ROM_ORIGINAL")
                    listarFTP("HACK")
                    listarFTP("KAIZO_HACK")
                    serverlabel.Text = "Total de HACKS no Servidor: " & ftplist.Items.Count
                Else
                    listarFTP(filtrobt.Text)
                    serverlabel.Text = "Total de HACKS na pasta " & filtrobt.Text & ": " & ftplist.Items.Count
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
                serverlabel.Text = "Erro ao tentar conectar com o servidor"
            End Try
        Else
            serverlabel.Text = "Servidor Desconectado"
        End If
    End Sub
    Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        icone.Visible = False
        Dim Processos() As Process = System.Diagnostics.Process.GetProcessesByName("zsnesw")
        For Each x As Process In Processos
            x.Kill()
        Next
    End Sub


    Private Sub facebookshare_Click(sender As Object, e As EventArgs) Handles facebookshare.Click
        Process.Start("https://www.facebook.com/sharer/sharer.php?u=http://mariohacks.url.ph/hacks/" & ftplist.SelectedItems.Item(0).SubItems.Item(2).Text & "/" & ftplist.SelectedItems.Item(0).Text)
    End Sub




    Sub VERIFICADOR_DATA()
        diretorio("ROMS")
        diretorio("ROMS\HACK")
        diretorio("ROMS\HACK")
        diretorio("ROMS\KAIZO_HACK")
        diretorio("ROMS\ROM_ORIGINAL")
        diretorio("ROMS\IMPORTADO")
        diretorio("IPS")
        diretorio("IMG")
        If File.Exists(CurDir() & "\DATA\zsnesw.exe") = False Then System.IO.File.WriteAllBytes(CurDir() & "\data\zsnesw.exe", My.Resources.zsnesw)
        If File.Exists(CurDir() & "\MarioHacksUpdater.exe") = False Then btupdate.Visible = False Else btupdate.Visible = True
    End Sub

    Function diretorio(path As String) As String
        Try
            If path.StartsWith("\") = False Or path.StartsWith("/") = False Then path = "\" & path
            If Directory.Exists(CurDir() & "\DATA") = False Then Directory.CreateDirectory(CurDir() & "\DATA")
            If Directory.Exists(CurDir() & "\DATA" + path) = False Then Directory.CreateDirectory(CurDir() & "\DATA" + path)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
        End Try
        Return CurDir() & "\DATA" & path.ToUpper
    End Function

    Function gerarcogumelo(arquivo As FileInfo) As Integer
        Dim cogumelo As Integer
        Select Case arquivo.Directory.Name
            Case "HACK"
                cogumelo = 5
            Case "ROM_ORIGINAL"
                cogumelo = 0
            Case "KAIZO_HACK"
                cogumelo = 3
            Case "IMPORTADO"
                cogumelo = 1
            Case Else
                cogumelo = 6
        End Select
        Return cogumelo
    End Function

    Sub listararquivos(Optional nomearquivo As String = "*")
        Dim pastacategoria As String = filtrobt.Text & "\"
        If pastacategoria = "TODAS\" Then pastacategoria = ""
        abas.SelectedTab = abajogos
        infobox.Text = "CARREGANDO HACKS..." & vbNewLine
        verificarprogs()
        pegarips()
        Try
            VERIFICADOR_DATA()

            listadejogos.Items.Clear()
            listadejogos.Groups.Clear()
            Dim diretorio As New DirectoryInfo(CurDir() & "\DATA\ROMS\" & pastacategoria)
            If String.IsNullOrWhiteSpace(pastacategoria) Then
                For Each dirs As DirectoryInfo In diretorio.GetDirectories
                    pegasoarquivo(dirs, nomearquivo)
                Next
            Else
                pegasoarquivo(diretorio, nomearquivo)
            End If

            locallabel.Text = "Total de HACKS Instaladas: " & listadejogos.Items.Count.ToString
            Me.Text = Environment.UserName & " @ MarioHacks Launcher"

        Catch ex As Exception

            MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Hand)

        End Try

    End Sub

    Sub pegasoarquivo(dirs As DirectoryInfo, Optional nomearquivo As String = "*")
        Dim arquivos As FileInfo() = dirs.GetFiles("*" & nomearquivo & "*.smc", SearchOption.AllDirectories)
        Dim grupo As New ListViewGroup(dirs.Name)
        listadejogos.Groups.Add(grupo)
        For Each arquivo As FileInfo In arquivos
            listadejogos.Items.Add(arquivo.Name.ToUpper, gerarcogumelo(arquivo)).Group = grupo
            infobox.AppendText("CARREGANDO HACK: " & arquivo.FullName & vbNewLine)
            listadejogos.Items(listadejogos.Items.Count - 1).SubItems.Add((Math.Round(arquivo.Length / 1024)).ToString() & " KB")
            listadejogos.Items(listadejogos.Items.Count - 1).SubItems.Add(arquivo.CreationTime.ToString)
            listadejogos.Items(listadejogos.Items.Count - 1).SubItems.Add(arquivo.Directory.Name.ToString.ToUpper)
            listadejogos.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            listadejogos.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
        Next
    End Sub
    Public nomeprint As String
    Dim imagem As Image
    Private Sub clicanalista(sender As Object, e As MouseEventArgs) Handles listadejogos.MouseClick
        Try
            nomeprint = listadejogos.SelectedItems.Item(0).Text
            If File.Exists(CurDir() & "\DATA\IMG\" & nomeprint & ".jpg") Then
                imagem = Image.FromFile(CurDir() & "\DATA\IMG\" & nomeprint & ".jpg")
                picrom.BackgroundImage = imagem


            Else
                picrom.BackgroundImage = My.Resources.errorblock
            End If
            picrom.BackgroundImageLayout = ImageLayout.Stretch
        Catch ex As Exception
        End Try

        Try
            nomeprint = listadejogos.SelectedItems.Item(0).Text
            loadrom.Text = "Jogar " & listadejogos.SelectedItems.Item(0).Text & " no ZSNES"
            loadlunar.Text = "Editar " & listadejogos.SelectedItems.Item(0).Text & " no Lunar Magic"
            mostradetalhes(listadejogos.SelectedItems.Item(0).SubItems.Item(3).Text, listadejogos.SelectedItems.Item(0).Text)
            If e.Button = Windows.Forms.MouseButtons.Right Then menurom.Show(MousePosition)

        Catch ex As Exception
        End Try

    End Sub

    Private Sub ToolStripButton1_Click_1(sender As Object, e As EventArgs) Handles trocaview.Click
        If sender.text = "LISTA" Then
            sender.text = "ICONES"
            listadejogos.View = View.LargeIcon
            ftplist.View = View.LargeIcon
        Else
            sender.text = "LISTA"
            listadejogos.View = View.Details
            ftplist.View = View.Details
        End If
    End Sub

    Sub mostradetalhes(categoria As String, oArquivo As String)
        infobox.Clear()
        Dim arquivo As New FileInfo(CurDir() & "\DATA\ROMS\" & categoria & "\" & oArquivo)
        Dim resposta As String
        infobox.AppendText("Nome do Arquivo: " & arquivo.Name & vbNewLine)
        infobox.AppendText("Diretório: " & arquivo.DirectoryName & vbNewLine)
        infobox.AppendText("Tamanho do Arquivo: " & arquivo.Length * 10 ^ -6 & " MB" & vbNewLine)
        infobox.AppendText("Data de Instalação: " & arquivo.CreationTime.ToString & vbNewLine)
        infobox.AppendText("Tipo de arquivo: " & arquivo.Extension & vbNewLine & vbNewLine)

        If File.Exists(arquivo.FullName.Replace(".SMC", ".srm")) = True Then resposta = "Sim" Else resposta = "Não"
        infobox.AppendText("Possui Saves? " & resposta & vbNewLine)

        If File.Exists(arquivo.FullName.Replace(".SMC", ".zst")) = True Then resposta = "Sim" Else resposta = "Não"
        infobox.AppendText("Possui Save States? " & resposta & vbNewLine)
        If File.Exists(CurDir() & "\DATA\IMG\" & nomeprint & ".jpg") Then infobox.AppendText("Captura de Tela: " & CurDir() & "\DATA\IMG\" & nomeprint & ".jpg" & vbNewLine)

        infobox.AppendText("Categoria: " & categoria)



    End Sub

    Private Sub infobox_TextChanged(sender As Object, e As EventArgs) Handles infobox.TextChanged
        infobox.DetectUrls = True
        infobox.ScrollToCaret()
    End Sub

    Private Sub ftplist_KeyDown(sender As Object, e As KeyEventArgs) Handles listadejogos.KeyDown, ftplist.KeyDown, infobox.KeyDown
        If e.KeyCode = Keys.F5 Then
            If sender Is ftplist Then LISTARSERVIDOR() Else listararquivos()
        End If
        If e.KeyCode = Keys.Enter Then
            If sender Is ftplist Then downloadit.PerformClick()
            If sender Is listadejogos Then loadrom.PerformClick()
        End If
        If e.KeyCode = Keys.Delete And sender Is listadejogos Then apagahack.PerformClick()
        If e.Control And e.KeyCode = Keys.F Then searchbar.Focus()
        If e.KeyCode = Keys.Home Then connectbutton.PerformClick()

    End Sub

    Private Sub ToolStripButton1_Click_2(sender As Object, e As EventArgs) Handles showlog.Click
        If showlog.Text = "Esconder Detalhes" Then
            showlog.Text = "Mostrar Detalhes"
            paineisprincipais.Panel2Collapsed = True
        Else
            showlog.Text = "Esconder Detalhes"
            paineisprincipais.Panel2Collapsed = False
        End If

    End Sub

    Sub printartela(processso As Process)
        AppActivate(emulador.Id)
        SendKeys.Send("%" + "{PRTSC}")
        Dim Screenshot As Image = Clipboard.GetImage()
        Screenshot.Save(CurDir() & "\DATA\IMG\" & nomeprint & ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
    End Sub

    Private Sub apagaprint_Click(sender As Object, e As EventArgs) Handles apagaprint.Click
        Try
            picrom.BackgroundImage = My.Resources.errorblock
            imagem.Dispose()
            Me.Update()
            File.Delete(CurDir() & "\DATA\IMG\" & nomeprint & ".jpg")
            infobox.Text = "Tela Apagada"
        Catch ex As Exception
            infobox.Text = "ERRO: " & ex.Message & " @ " & ex.Source
        End Try
    End Sub

    Private Sub listadejogos_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles listadejogos.MouseDoubleClick
        loadrom.PerformClick()
    End Sub

    Private Sub downloadit_Click_1(sender As Object, e As EventArgs) Handles downloadit.Click
        rotinadedownload()
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btupdate.Click
        Try
            Process.Start(CurDir() & "\MarioHacksUpdater.exe")
            End
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
        End Try
    End Sub
    
    Private Sub ToolStripTextBox1_Click(sender As Object, e As KeyEventArgs) Handles searchbar.KeyDown
        listararquivos(sender.text)
    End Sub


     
End Class


